package org.dragonnova.meetingclient.core.net.netty;

import android.util.Log;

import org.dragonnova.meetingclient.core.manager.NettyManager;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * Created by hucn on 2016/5/19.
 * Description: Netty框架的服务端
 */
public class NettyClient {

    private static final String TAG = NettyClient.class.getName();
    private NettyManager.NettyClientHandler mNettyClientHandler;
    private Bootstrap mBootstrap;
    private EventLoopGroup mGroup;
    public ChannelFuture mChannelFuture;
    private Channel mChannel;
    boolean waitFlag;


    public NettyClient(NettyManager.NettyClientHandler nettyClientHandler) {
        this.mNettyClientHandler = nettyClientHandler;
        initNettyClient();
    }

    private void initNettyClient() {
        // 配置客户端NIO线程组
        try {
            // 客户端辅助启动类 对客户端配置
            mGroup = new NioEventLoopGroup();
            mBootstrap = new Bootstrap();
            mBootstrap.group(mGroup).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChildChannelHandler());
        } catch (Exception e) {
            e.printStackTrace();
            releaseResource();
        }
    }

    /**
     * 连接服务器
     *
     * @throws Exception
     */
    public void connect(String host, int port) {
        // 配置客户端NIO线程组
        try {
            // 异步链接服务器 同步等待链接成功
            mChannelFuture = mBootstrap.connect(host, port).sync();
            mChannel = mChannelFuture.channel();
            Log.i(TAG, "=====client===start==");
            mChannel.closeFuture().sync();
            Log.i(TAG, "=====client===close==");
        } catch (Exception e) {
            e.printStackTrace();
            releaseResource();
        }
    }

    public void releaseResource() {
        // 等待链接关闭
        setFlag(false);
        try {
            if (mChannelFuture != null) {
                if (mChannel != null) {
                    mChannel.close();
                    mChannel = null;
                }
                mChannelFuture = null;
            }
            // 优雅退出 释放线程池资源
            if (mGroup != null) {
                mGroup.shutdownGracefully();
                mGroup = null;
            }
            Log.i(TAG, "客户端优雅的释放了线程资源...");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setFlag(boolean flag) {
        this.waitFlag = flag;
    }

    /**
     * 网络事件处理器
     */
    @ChannelHandler.Sharable
    private class ChildChannelHandler extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            Log.i(TAG, "SocketChannel.id=" + ch.id());
            ch.pipeline().addLast(new IdleStateHandler(20, 20, 0));
            ch.pipeline().addLast("decoder", new MsgDecoder());
            ch.pipeline().addLast("encoder", new MsgEncoder());
            ch.pipeline().addLast(mNettyClientHandler);
        }
    }
}
